package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniu.util.StringUtils;
import io.renren.common.annotation.DataFilter;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.sys.dao.SysDeptDao;
import io.renren.modules.sys.entity.SysDeptEntity;
import io.renren.modules.sys.service.SysDeptService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 部门管理实现
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-06-20 15:23:47
 */
@Service("sysDeptService")
public class SysDeptServiceImpl extends ServiceImpl<SysDeptDao, SysDeptEntity> implements SysDeptService {

  @Override
  public PageUtils queryPage(Map<String, Object> params) {

    Page<SysDeptEntity> page = (Page<SysDeptEntity>) this.page(
            new Query<SysDeptEntity>(params).getPage(),
            new QueryWrapper<SysDeptEntity>()
                    .eq("del_flag", 0)
    );

    return new PageUtils(page);
  }

  @Override
  @DataFilter(deptAlias = "d.dept_id")
  public List<SysDeptEntity> queryList(Map<String, Object> map){
    return baseMapper.queryList(map);
  }

  @Override
  public boolean insert(SysDeptEntity sysDept){
    return this.save(sysDept);
  }

  @Override
  public boolean update(SysDeptEntity sysDept){
    return this.updateById(sysDept);
  }

  @Override
  public List<Long> queryDetpIdList(Long parentId) {
    return baseMapper.queryDetpIdList(parentId);
  }

  @Override
  public String getSubDeptIdList(Long deptId){
    //部门及子部门ID列表
    List<Long> deptIdList = new ArrayList<>();

    //获取子部门ID
    List<Long> subIdList = queryDetpIdList(deptId);
    getDeptTreeList(subIdList, deptIdList);

    //添加本部门
    deptIdList.add(deptId);

    String deptFilter = StringUtils.join(deptIdList, ",");
    return deptFilter;
  }

  /**
   * 递归
   */
  private void getDeptTreeList(List<Long> subIdList, List<Long> deptIdList){
    for (Long deptId : subIdList){
      List<Long> list = queryDetpIdList(deptId);
      if (list.size() > 0) {
        getDeptTreeList(list, deptIdList);
      }

      deptIdList.add(deptId);
    }
  }
}